<template>
	
	<view class="wrap" >
	
		<!-- 頭部信息 -->
		<detailInfo :stockDetail="stockDetail" :id="id"></detailInfo>
		<!-- 時間選項 -->
		<view class="wrap__option">
			<text :class="['option__item', timeIndex===index?'option__item--active':'']" 
			v-for="(item, index) in timeOptions" :key="index" @click="timeChange(index)">{{item.name}}</text>
		</view>
		<view class="wrap__ma">
			<text class="ma__item" id="MA5"></text>
			<text class="ma__item" id="MA10"></text>
			<text class="ma__item" id="MA20"></text>
			<text class="ma__item" id="MA30"></text>
		</view>
		<!-- k綫圖 -->
		<view class="wrap__cate" id="chart" :title="stockDetail.category_id"></view>
		<view class="wrap__chart" :keyLineData="keyLineData" :change:keyLineData="keyLine.dataChange">
			<view :class="['chart__main', 'chart__main--'+ styleIndex]" id="kLine"></view>
		</view>
		<!-- 排行榜 -->
		<tradeRank :handicapInfo="handicapInfo" :dealRecords="dealRecords"></tradeRank>
		<!-- 操作按钮 -->
		<view class="wrap__btn">
			<text class="btn__text" @click="buyClick">{{$t('stock.buy')}}</text>
			<text class="btn__text" @click="sellClick">{{$t('stock.sell')}}</text>
		</view>
		<!-- 买卖操作-->
		<tradeOption v-if="isShowTrade" :btnType="btnType" :stockDetail="stockDetail"
		 :isShowTrade.sync="isShowTrade" @updateDetail="getStockDetail"></tradeOption>
	</view>
</template>

<script>
	import detailInfo from '@/components/account/detailInfo.vue'
	import tradeOption from '@/components/account/tradeOption.vue'
	import tradeRank from '@/components/account/tradeRank.vue'
	import { formatDate } from "@/common/js/utils"
	export default{
		components:{
			tradeOption,
			tradeRank,
			detailInfo
		},
		data(){
			return {
				isShowTrade:false,
				id:"",
				stockDetail:{}, //股票详情
				btnType:1, // 1買 0賣 
				handicapInfo:{}, //盘口数据信息
				dealRecords:[], // 成交列表
				timerId:null,
				info:{},
				keyLineData:[], //k綫圖數據
				timeOptions:[ //時間選項
					{name:"1M", value:"PT1M"},
					{name:"5M", value:"PT5M"},
					{name:"15M", value:"PT15M"},
					{name:"30M", value:"PT30M"},
					{name:"1H", value:"PT1H"},
					{name:"5H", value:"PT5H"},
					{name:"1W", value:"P1W"},
					{name:"1M", value:"P1M"}
					],
				timeIndex:2, // 选项索引
				styleIndex:0,
				isShowLoading:true
			}
		},
		onUnload() {
			clearInterval(this.timerdetail)
		},
		onHide() {
			clearInterval(this.timerdetail)
		},
		async onShow() {
			
			const wsUrl = 'wss://streaming.forexpros.com/echo/620/1h0r2drb/websocket'; // 替换为你的wss服务器地址
			this.ws = uni.connectSocket({
			  url: wsUrl,
			  complete: () => {}
			});
							 
			this.ws.onOpen(() => {
			  console.log('WebSocket连接已打开！');
			  this.ws.send({
			      data: ["{\"_event\":\"bulk-subscribe\",\"tzID\":8,\"message\":\"%%pid-"+this.id+":\"}"],
			      success: () => {
			        console.log('消息发送成功！');
			      },
			      fail: () => {
			        console.log('消息发送失败！');
			      }
			    });
			});
							 
							 
							 
		   			 
			this.ws.onMessage((message) => {
			
			  const str = message.data
			  const index = str.indexOf('::');
			  
			  if (index !== -1) {
			      // 截取 :: 之后的子字符串
			      const subString = str.substring(index + 2);
				  const newStr = subString.slice(0, -4);
				  const newStr1 = newStr.replace(/\\\\|\\/g, '');
			     
				  
				  const jsonObject = JSON.parse(newStr1);
				  
				  
				
				  if(this.id == jsonObject.pid){
					  
					  
					  
					   
					  this.stockDetail.price =  parseFloat(jsonObject.last.replace(',', ''))
					  
					  this.stockDetail.zhangdiebaifenbi = jsonObject.pcp.replace(/\%/g, '')
					  
					  this.stockDetail.zhangdieshu = jsonObject.pc.replace(/\%/g, '')
					  // this.stockDetail.open = jsonObject.ask
					  // this.stockDetail.close = jsonObject.last
					  this.stockDetail.high = parseFloat(jsonObject.high.replace(',', '')) 
					  this.stockDetail.low = parseFloat(jsonObject.low.replace(',', ''))
					
					  this.stockDetail.id = jsonObject.pid
					
					  this.stockDetail.zongshizhi = jsonObject.turnover
					  // this.stockDetail.zongshizhi = jsonObject.turnover_numeric
					  
					
					  let res =   this.$api.chuli(this.stockDetail)
					  
					  
					
				
				  }
				   
			  } 
			  // 将字符串解析为 JSON 对象
			
			  
			 
			});
							 
			this.ws.onError((error) => {
			  console.error('WebSocket连接发生错误：', error);
			});
							 
			this.ws.onClose(() => {
			  console.log('WebSocket已关闭！');
			});
			
			
		
		},
		async onLoad(options) {
			let kStyle = uni.getStorageSync("kStyle")
			if(kStyle){
				this.styleIndex = kStyle
			}
			this.id = options.id
			
			
			 if(!options.info){
				 await this.getStockDetail()
				
			 }else{
				  this.info = JSON.parse(decodeURIComponent(options.info))
				  
				 //let res1 = await this.$api.getStockDetail(this.id)
				 // if(res.code === 1 && res.data){
				 // 	this.stockDetail.amount = res.data.amount
				 // 	this.stockDetail.chicang = res.data.chicang
				 // }
				 await this.getStockDetail(1)
				 
				
				 
				
				 // 获取定时数据
				 await this.gupiaoDetail()
			 }
			 
			
			// 獲取詳情
			
			 
		
			
			await this.getHandicapInfo()
			
			await this.getKeyLine()
			//获取股票详情数据
			
			      
		
			
			
		},
		beforeDestroy() {
			this.timerId && clearInterval(this.timerId)
		},
		methods:{
			//定时获取盘口 交易记录
			getTimeData(){
				
				// 获取k线图
				// this.getKeyLine()
				// // 获取盘口数据
				// this.getHandicapInfo()
				// // 获取交易记录数据
				// this.getDealRecords()
			},
			
			async gupiaoDetail() {
			
			
				
				
				
				
				
				 this.stockDetail.id = this.info.Id
				
				// // let info = res.d.v
				this.stockDetail.price = this.info.Last
				this.stockDetail.zhangdiebaifenbi = this.info.zhangdiebaifenbi
				this.stockDetail.zhangdieshu = this.info.zhangdieshu
				this.stockDetail.name = this.info.Name
				this.stockDetail.open = this.info.Last
				
				this.stockDetail.high = this.info.High
				this.stockDetail.low = this.info.Low
				this.stockDetail.turnover = this.info.FundamentalMarketCap
				this.stockDetail.zongshizhi = this.info.AvgVolume
				 this.stockDetail.shuzidaima = this.info.Symbol
				 this.stockDetail.zimudaima = this.info.Symbol
				 this.stockDetail.flag = this.info.Flag
				
				
			
				
				let res = await  this.$api.chuli(this.stockDetail)
				 
			},
			// 获取盘口数据
			async getHandicapInfo(){
				let res = await this.$api.getHandicapList(this.id)
				if(res.code === 1 && res.data){
					this.handicapInfo = res.data
				}
			},
			// 获取交易记录数据
			async getDealRecords(){
				let res = await this.$api.getDealRecords(this.id)
				if(res.code === 1 && res.data){
					// console.log('成交数据', res.data)
					this.dealRecords = res.data // 交易记录
				}
			},
			// 获取K线图
			async getKeyLine(){
				let {timeOptions, timeIndex} = this
				let {value} = timeOptions[timeIndex]
				//let res = await this.$api.getKeyLine(this.id, value)
				
				uni.request({
				    url: 'https://api.investing.com/api/financialdata/'+this.id+'/historical/chart/?interval='+value+'&pointscount=110',
					method: 'GET',
				    data: {},
				    success: (res) => {
				       

						let list = res.data?.data || []
						
						let timeStr = value.includes("M")?"Y-m":"m-d"
						this.keyLineData  = list.map(item=>{
							item[0] = formatDate( item[0], timeStr) 
							return item
						})
						
						this.isShowLoading = false
						uni.hideLoading()
				    },
				    fail: (err) => {
				        console.error(err); // 请求失败的错误信息
				    }
				});
				
				
				
				
				// if(res && res.code === 1 && res.data){
				// 	if(res.data.length){
				// 		// 处理时间格式
				// 		let timeStr = value.includes("M")?"Y-m":"m-d"
				// 		this.keyLineData = res.data.map(item=>{
				// 			item[0] = formatDate( item[0], timeStr) 
				// 			return item
				// 		})
				// 	}else{
				// 		this.keyLineData = []
				// 	}
				// 	this.isShowLoading = false
				// 	uni.hideLoading()
				// }else{
				// 	uni.hideLoading()
				// 	uni.showToast({
				// 		title:res.msg,
				// 		icon:"none"
				// 	})
				// }
			},
			// 買點擊
			buyClick(){
				this.btnType = 1
				this.isShowTrade = true
			},
			//賣點擊
			sellClick(){
				this.btnType = 0
				this.isShowTrade = true
			},
			// 获取股票详情
			async getStockDetail(type1){
				
				let res = await this.$api.getStockDetail(this.id)
				
				
				if(res.code === 1 && res.data){
					
				
					this.stockDetail = res.data
					
					
					//此处处理价格
					//现货区关盘价格
					let close_url = 'https://api.investing.com/api/financialdata/'+this.id+'/historical/chart/?interval=P1D&pointscount=60';
					let close_price = 0;
					let price = 0;
					let bili = 0;
					let open = 0;
					let qian_open = 0;
					let bao_price = 0;
					let small_close_price = 0;
					
					const today = new Date();

					const yesterday = new Date(today);
					yesterday.setDate(today.getDate() - 1);
					
					
					
					// 格式化日期
					const year = yesterday.getFullYear();
					const month = String(yesterday.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以要加 1
					const day = String(yesterday.getDate()).padStart(2, '0');
					
					// 昨天的日期字符串（格式为 YYYY-MM-DD）
					const yesterdayString = `${year}-${month}-${day}`;
					

                 
                  // 获取年、月和日
                  const year1 = today.getFullYear();
                  const month1 = String(today.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以要加 1
                  const day1 = String(today.getDate()).padStart(2, '0');
                  
                  // 构建日期字符串（格式为 YYYY-MM-DD）
                  const todayString = `${year1}-${month1}-${day1}`;
			
						uni.request({
						    url: close_url,
							method: 'GET',
						    data: {},
						    success: (res) => {
						      
								let list = res.data.data
								
								let keyo = 0
					
							   list.map(item=>{
									
									// 创建一个新的 Date 对象并传入毫秒数
									const date = new Date(item[0]);
									
									
									// 获取年、月和日
									const year = date.getFullYear();
									const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从 0 开始，所以要加 1
									const day = String(date.getDate()).padStart(2, '0');
									
									// // 构建日期字符串（格式为 YYYY-MM-DD）
									// const dateString = `${year}-${month}-${day}`;
									// if(dateString == yesterdayString){
									// 	close_price = item[4]
									// }
									
									//   const date1 = new Date(yesterdayString);
									//   date1.setDate(date1.getDate() - 1); // 减去一天
									//   const uuds =  date1.toISOString().split('T')[0];
									// if(dateString == uuds){
									// 	small_close_price = item[4]
									// }
									
									
									bao_price  = item[4]
									
									
									// if(dateString == uuds){
									// 	open = item[1]
									// }
									
									// if(dateString == todayString){
									// 	open = item[1]
									// }
									
									open = item[1]
									
									
									
								
								})
								
								
								
								close_price = list[list.length-2][4]
								
								
								
								
								
								
								
								
								let close_url1 = 'https://api.investing.com/api/financialdata/'+this.id+'/historical/chart/?interval=PT5M&pointscount=110';
								
							
								uni.request({
								    url: close_url1,
									method: 'GET',
								    data: {},
								    success: (res) => {
								      
										let list = res.data.data
													
									   list.map(item=>{
											
											price = item[4]
											
										})
										
										
										
										
										if(price && close_price){
											
											
											//small_close_price
											
											if(type1){
												
												this.stockDetail.open = open
												this.stockDetail.close = close_price
											}else{
												
												// if(price == close_price){
													
												// 	this.stockDetail.zhangdiebaifenbi = (price - small_close_price)/small_close_price
												// 	this.stockDetail.zhangdieshu = price - small_close_price
												//       this.stockDetail.close = small_close_price				
												// }else{
												// 	this.stockDetail.zhangdiebaifenbi = (price - close_price)/close_price
												// 	this.stockDetail.zhangdieshu = price - close_price
												// 	this.stockDetail.close = close_price				
												// }
												
												this.stockDetail.zhangdiebaifenbi = (price - close_price)/close_price
												this.stockDetail.zhangdieshu = price - close_price
												this.stockDetail.close = close_price
												
												this.stockDetail.zhangdiebaifenbi = this.stockDetail.zhangdiebaifenbi * 100
												
												this.stockDetail.price = price
												
																						
												this.stockDetail.open = open
																		
												
												
												this.stockDetail.zhangdiebaifenbi = this.stockDetail.zhangdiebaifenbi.toFixed(2)
												this.stockDetail.zhangdieshu = this.stockDetail.zhangdieshu.toFixed(2)
												let res =   this.$api.chuli(this.stockDetail)
											}
											
																	
										}
										
								    }
								});
							
						    }
						});
						
						
						
						
				
				
				
				}
			},
			// 時間選項切換
			async timeChange(index){
				if(this.timeIndex !== index){
					this.timeIndex = index
					if(this.timeIndex == 0 || this.timeIndex == 1){
						uni.showLoading({
							title: this.$t('loading.loading'),
							mask:true
						})
					}
					try{
						await this.getKeyLine()
						uni.hideLoading()
					}catch(e){
						uni.hideLoading()
					}
				}
			}
		},

	}
</script>
<script module="keyLine" lang="renderjs">
	import { formatDate } from "@/common/js/utils"
	window.wx = {}
	// 获取指定区间随机数
	function sum (m,n){
	　　var num = Math.floor(Math.random()*(m - n) + n);
		 return num;
	}
	// 语言配置
	let langConfig = {
		cn:{
			time:"時間",
			title:"履歴",
			high:"高値",
			low:"です",
			close:"引けます",
			deal:"成約です"
		},
		en:{
			time:"Date",
			title:"Open",
			high:"Highest",
			low:"Lowest",
			close:"Close",
			deal:"Deal"
		},
		kro:{
			time:"時間",
			title:"履歴",
			high:"高値",
			low:"です",
			close:"引けます",
			deal:"成約です"
		},
	}
	let myChart
	export default {
		data() {
			return {
				rawData:[], //K线数据
				dates:[], //日期
				data:[], //股价数据
				volumes:[], 
				MA5:'',
				MA10:'',
				MA30:'',
				volMA5:'',
				volMA10:'',
			}
		},
		beforeDestroy(){
			myChart = null
		},
		methods: {
			// 設置K线數據
			setLineData(rawData){
				this.rawData = rawData
				this.dates = rawData.map(function(item) { //日期
					return  item[0];
				});
				this.data = rawData.map(function(item) {
					// 重新排序 开盘 收盘 最低  最高
					return [+item[1], +item[4], +item[3], +item[2], +item[5]];
				});
				// 柱线图 item[1] > item[4] 开盘 收盘价 
				this.volumes = rawData.map(function(item, index) {
					return [index, item[5], item[1] > item[4] ? 1 : -1];
				});
			},
			// key line數據變化
			dataChange(data){
				if(data.length){
					this.setLineData(data)
				}
				// 
				if (typeof window.echarts === 'function') {
					this.initEcharts()
				} else {
					// 动态引入较大类库避免影响页面展示
					const script = document.createElement('script')
					// view 层的页面运行在 www 根目录，其相对路径相对于 www 计算
					script.src = '/static/echarts.min.js'
					script.onload = this.initEcharts.bind(this)
					document.head.appendChild(script)
				}
			},
			// 初始化echarts
			initEcharts() {
				if(!myChart){
					myChart = echarts.init(document.getElementById('kLine'));
					this.draw()
				}
				if(this.data.length){
					this.getKline()
				}
			},
		 calculateMA(dayCount, data) {
			  var result = [];
			  for (var i = 0, len = data.length; i < len; i++) {
			    if (i < dayCount) {
			      result.push('-');
			      continue;
			    }
			    var sum = 0;
			    for (var j = 0; j < dayCount; j++) {
			      sum += +data[i - j][1];
			    }
			    result.push(sum / dayCount);
			  }
			  return result;
			},
			// 获取k线数据,生成k线
			getKline(){
				var dataMA5 = this.calculateMA(5, this.data);
				var dataMA10 = this.calculateMA(10, this.data);
				var dataMA20 = this.calculateMA(20, this.data);
				var dataMA30 = this.calculateMA(30, this.data);
				var volumeMA5 = this.calculateMA(5, this.volumes);
				var volumeMA10 = this.calculateMA(10, this.volumes);
				let scaleStart = 0
				let dataLength = this.rawData.length
				if(dataLength>=40){
					if(dataLength >=40 && dataLength < 60){
						scaleStart = 50
					}else if(dataLength >=60 && dataLength < 100){
						 scaleStart = 70
					}else if(dataLength >=100 && dataLength <= 170){
						scaleStart = 75
					}else if(dataLength > 170 && dataLength <= 200){
						scaleStart = 80
					}else if(dataLength > 200 && dataLength <= 250){
						scaleStart = 85
					}else{
						scaleStart = 88
					}
				}
				let maxData = "dataMax"
				if(dataLength <= 10){
					maxData = 20
				}
				myChart.setOption({
					xAxis: [
						{
							data: this.dates,
							max:maxData,
						},
						{
							data: this.dates,
							max:maxData,
						},
					],
					dataZoom: [{ //用于区域缩放
						type: 'inside',
						xAxisIndex: [0, 1],
						realtime: false,
						start:scaleStart,
						end: 110,
					}
					],
					series: [
						{ 
							name: '日K', //key线图数据
							data: this.data
						},
						{
							name: 'MA5', //折线图
							data: this.calculateMA(5, this.data),
						
						},
						{
							name: 'MA10',
							data: this.calculateMA(10, this.data),
						},
						{
							name: 'MA20',
							data: this.calculateMA(20, this.data),
						},
						{
							name: 'MA30',
							data: this.calculateMA(30, this.data),
						},
						{
							name: 'Volume',
							data: this.volumes
						},
					]
				})
			},
			// 截取数字字符串 保留precision小数
			formatterNum(value, precision) {
				let reg = new RegExp('^\\d+(?:\\.\\d{0,' + precision + '})?')
				return value.toString().match(reg)
			},
			// 计算MA
			calculateMA(dayCount, data) {
				var result = [];
				for (var i = 0, len = data.length; i < len; i++) {
					if (i < dayCount) {
						result.push('-');
						continue;
					}
					var sum = 0;
					for (var j = 0; j < dayCount; j++) {
						sum += data[i - j][1];
					}
					result.push((sum / dayCount).toFixed(2));
				}
				return result;
			},
			// 绘制(配置项) 时间  开盘价  最高 最低 收盘 成交量
			draw(){
				let that=this;
				let chartDom = document.getElementById("chart")
				 // cateId 1韩 2美 3港   美股 港股 绿涨红跌 韩股红涨绿跌 03ad91  dd345b
				let cateId = chartDom.title || ""
				let upColor = cateId === "1" ?  '#03ad91' : "transparent" //红涨
				let upBorderColor = cateId === "1" ?  '#03ad91' : "#dd345b" 
				let downColor = upColor === "#03ad91" ? 'transparent': '#03ad91'; // 跌价
				let downBorderColor = upBorderColor === "#03ad91" ? '#dd345b':"#03ad91"
				let colorList = ['#dd345b', '#2f4554', '#dd345b', '#d48265', '#dd345b', '#749f83', '#ca8622', '#bda29a', '#6e7074',
					'#546570', '#c4ccd3'
				];
				let labelFont = 'bold 12px Sans-serif';
				let option = { //#0d1723
					// backgroundColor: '#0d1723',
					barWidth: 4,
					
					title: {
						show: false
					},
					legend: {
						show: false
					},
					visualMap: {
							show: false,
							seriesIndex: 5, // 數據索引
							dimension: 2,
							pieces: [{
									value: 1,
									color: downBorderColor  //downColor
							}, {
									value: -1,
									color: upBorderColor //upColor
							}]
					},
					grid: [{
							top: '5%',
							left: 10,
							right: 50,
							height: '70%'
						},
						{
							top: '75%',
							left: 10,
							right: 50,
							height: '16%'
						},
					],
					axisPointer: { //坐标轴指示器配置项
						link: {
							xAxisIndex: 'all'
						},
						label: {
							backgroundColor: '#0d1723',
							color: '#63758b',
							borderColor: 'rgb(99, 117, 139)',
							borderWidth: 1,
							borderRadius: 2,
							fontSize: 10
						}
					},
					xAxis: [{
						minInterval: 1,
						type: 'category', //坐标轴类型。(value:数值轴，适用于连续数据。,category:类目轴，适用于离散的类目数据,time: 时间轴，适用于连续的时序数据,log:对数轴。适用于对数数据)
						data: [], //类目数据，在类目轴（type: 'category'）中有效。
						scale: true,
						boundaryGap: false, //坐标轴两边留白策略，类目轴和非类目轴的设置和表现不一样。
						axisLine: {
							show: true,
							lineStyle: {
							        color: '#d4d1d1' // 设置 x 轴的颜色为红色
							}
						}, //坐标轴轴线相关设置
						
						axisTick: {
							 alignWithLabel: true, // 刻度线与标签对齐
						}, //坐标轴刻度相关设置。
						axisLabel: {
							  // interval: 0, // 设置标签全部显示
								　showMaxLabel:true,
								　showMinLabel:true　
							// show: false,
						}, //坐标轴刻度标签的相关设置。
						splitLine: {
							 show: true,   // 显示网格线
							      lineStyle: {
							        type: 'dashed', // 设置网格线的类型为虚线
							        color: '#63758b',  // 设置虚线的颜色
							      },
						},  //坐标轴在 grid 区域中的分隔线。
						min: 'dataMin', //坐标轴刻度最小值。可以设置成特殊值 'dataMin'，此时取数据在该轴上的最小值作为最小刻度。
						max: 'dataMax', //坐标轴刻度最大值。可以设置成特殊值 'dataMax'，此时取数据在该轴上的最大值作为最大刻度。
						axisPointer: {
							label: {
								margin: 200
							}
						},
					
					}, {
						type: 'category',
						gridIndex: 1, //x 轴所在的 grid 的索引，默认位于第一个 grid。
						data: [], //类目数据，在类目轴（type: 'category'）中有效。
						scale: true,
						boundaryGap: false, //坐标轴两边留白策略，类目轴和非类目轴的设置和表现不一样。
						axisLine: {
							show: false,
							lineStyle: {
								color: '#63758b',
								width: 1
							}
						}, //坐标轴轴线相关设置
						axisTick: {
							show: false
						}, //坐标轴刻度相关设置。
						axisLabel: { //坐标轴刻度标签的相关设置。
							show: true,
							margin: 6,
							fontSize: 10,
							color: '#63758b',
							// formatter: function(value) { //时间格式化
							// 	return echarts.format.formatTime('MM-dd', value);
							// }
						},
						splitLine: {
							show: false,
							lineStyle: {
								color: 'rgba(255,255,255, 0.1)'
							}
						}, //坐标轴在 grid 区域中的分隔线。
						min: 'dataMin', //坐标轴刻度最小值。可以设置成特殊值 'dataMin'，此时取数据在该轴上的最小值作为最小刻度。
						max: 'dataMax', //坐标轴刻度最大值。可以设置成特殊值 'dataMax'，此时取数据在该轴上的最大值作为最大刻度。
						// axisPointer: { show: true, type: 'none', label: { show: false }},
					}],
					yAxis: [{
						show:true,
						type: 'value', //坐标轴类型。(value:数值轴，适用于连续数据。,category:类目轴，适用于离散的类目数据,time: 时间轴，适用于连续的时序数据,log:对数轴。适用于对数数据)
						position: 'right', //y 轴的位置。'left','right'
						scale: true, //是否是脱离 0 值比例。设置成 true 后坐标刻度不会强制包含零刻度。在双数值轴的散点图中比较有用。(在设置 min 和 max 之后该配置项无效。)
						axisLine: {
							show: true,
							lineStyle: {
							        color: '#63758b' // 设置 x 轴的颜色为红色
							}
						}, //坐标轴轴线相关设置。
						
						axisTick: {
							show: false,
							inside:true
						}, //坐标轴刻度相关设置。
						axisLabel: { //坐标轴刻度标签的相关设置。
							show: true,
							color: '#63758b',
							// inside: true,
							fontSize: 10,
							formatte : function(value) {
								if(value >= 1000){
									return Number(value / 1000).toFixed(2) + "k"
								}
								return Number(value).toFixed(2)
							}
						},
						splitLine: {
							 show: true,   // 显示网格线
							      lineStyle: {
							        type: 'dashed', // 设置网格线的类型为虚线
							        color: '#63758b',  // 设置虚线的颜色
							      },
						}, //坐标轴在 grid 区域中的分隔线。
					}, {
						type: 'value',
						position: 'right',
						show:false,
						scale: true,
						gridIndex: 1,
						axisLine: {
							show: false
						},
						axisTick: {
							show: false
						},
						axisLabel: {
							show: false
						},
						splitLine: {
							show: false
						}
					}],
					animation: false, //是否开启动画。
					color: colorList,
					tooltip: {
						show: true, //是否显示提示框组件，包括提示框浮层和 axisPointer。
						trigger: 'axis', //触发类型。item,axis,none
						formatter(params){
							let tooltip = '';
							// 本地语言
							let LocalLan = localStorage.getItem("language")
							let time = '', open = 0, high = 0, low = 0, close = 0, amount = 0;
							for (var i = 0; i < params.length; i++) {
								if (params[i].seriesName === '日K') {
									time = params[i].name;
									open = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[1], 2)) : 0;  //开盘价
									close = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[2], 2)) : 0; //收盘
									low = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[3], 2)) : 0; //最低
									high = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[4], 2)) : 0; //最高
									amount = params[i].data.length > 1 ? Number(that.formatterNum(params[i].data[5], 2))  : 0; //成交量
									amount = (amount / 100).toFixed(1)

									tooltip = '<div class="charts-tooltip">' +
										'<div class="charts-tooltip-row"><div class="ctr-label">' + langConfig[LocalLan].time + '</div><div class="ctr-value">' + time + '</div></div>' + 
										'<div class="charts-tooltip-row"><div class="ctr-label">' + langConfig[LocalLan].title + '</div><div class="ctr-value">' + open + '</div></div>' + 
										'<div class="charts-tooltip-row"><div class="ctr-label">' + langConfig[LocalLan].high + '</div><div class="ctr-value">' + high + '</div></div>' + 
										'<div class="charts-tooltip-row"><div class="ctr-label">' + langConfig[LocalLan].low + '</div><div class="ctr-value">' + low + '</div></div>' + 
										'<div class="charts-tooltip-row"><div class="ctr-label">' + langConfig[LocalLan].close + '</div><div class="ctr-value">' + close + '</div></div>' + 
										'<div class="charts-tooltip-row"><div class="ctr-label">' + langConfig[LocalLan].deal + '</div><div class="ctr-value">' +amount + 'K'+ '</div></div></div>';
								}
								if (params[i].seriesName === 'MA5') {
									let MA5 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
									if(MA5 > 1000){
										MA5 = (MA5 / 1000).toFixed(2) + "K"
									}
									document.getElementById("MA5").innerText = `MA5 ${MA5}`
								}
								if (params[i].seriesName === 'MA10') {
									let MA10 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
									if(MA10 > 1000){
										MA10 = (MA10 / 1000).toFixed(2) + "K"
									}
									document.getElementById("MA10").innerText = `MA10 ${MA10}`
								}
								if (params[i].seriesName === 'MA20') {
									let MA20 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
									if(MA20 > 1000){
										MA20 = (MA20 / 1000).toFixed(2) + "K"
									}
									document.getElementById("MA20").innerText = `MA20 ${MA20}`
								}
								if (params[i].seriesName === 'MA30') {
									let MA30 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
									if(MA30 > 1000){
										MA30 = (MA30 / 1000).toFixed(2) + "K"
									}
									document.getElementById("MA30").innerText = `MA30 ${MA30}`
								}
								if (params[i].seriesName === 'VolumeMA5') {
									that.volMA5 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
								}
								if (params[i].seriesName === 'VolumeMA10') {
									that.volMA10 = params[i].data !== 'NAN' ? Number(that.formatterNum(params[i].data, 2)) : 0
								}
							}
							return tooltip;
						},
						triggerOn: 'click', //提示框触发的条件 'mousemove','click','mousemove|click','none'
						textStyle: {
							fontSize: 10
						}, //提示框浮层的文本样式
						backgroundColor: 'rgba(30,42,66,0.8);', //提示框浮层的背景颜色。
						borderColor: '#2f3a56', //提示框浮层的边框颜色。
						borderWidth:2,
						position: function(pos, params, el, elRect, size) { //提示框浮层的位置，默认不设置时位置会跟随鼠标的位置。
							var obj = {
								top: 20
							};
							obj[['left', 'right'][+(pos[0] < size.viewSize[0] / 2)]] = 10;
							return obj;
						},
						axisPointer: { //坐标轴指示器配置项。
							label: {
								show:false,
								color: '#f10', //rgba(255,255,255,.87)
								fontSize: 9,
								backgroundColor: '#020204',
								borderColor: "#9c9fa4",
								shadowBlur: 0,
								borderWidth: 0.1,
								padding: [4, 2, 3, 2],
							},
						// 	animation: false,
							type: 'cross',
							lineStyle: {
								color:"#aaa",
								width: 1,
								type:"dashed"
							}
						}
					},
					dataZoom: [{ //用于区域缩放
						zoomLock: true,
						preventDefaultMouseMove:false,
						type: 'inside',
						xAxisIndex: [0, 1],
						realtime: false,
						start:80,
						end: 100,
					},
					],
					series: [
						{
							type: 'candlestick',
							name: '日K',
							data: [],
							
							itemStyle: {
								color: upColor,
								color0: downColor,
								borderColor: upBorderColor,
								borderColor0: downBorderColor
							},
							markPoint: {
								symbol: 'rect',
								symbolSize: [-10, 0.5],
								symbolOffset: [5, 0],
								itemStyle: {
									color: 'rgba(255,255,255,.87)'
								},
								label: {
									color: '#fff',
									offset: [10, 0],
									fontSize: 10,
									align: 'left',
									formatter: function(params) {
										let num = Number(params.value)
										if(num > 1000){
											return (num / 1000).toFixed(2) + "K"
										}
										return Number(params.value).toFixed(2)
									}
								},
								data: [{
										name: 'max',
										type: 'max',
										valueDim: 'highest'
									},
									{
										name: 'min',
										type: 'min',
										valueDim: 'lowest'
									}
								]
							},
						}, 
						
						{
							name: 'MA5',
							type: 'line',
							data: [],
							symbol: 'none',//去除圆点
							smooth: true,
							lineStyle: { normal: { opacity: 1, width: 2, color: "#ffa500" } },
							z: 5
						}, 
						{
							name: 'MA10',
							type: 'line',
							data: [],
							symbol: 'none',//去除圆点
							smooth: true,
							lineStyle: { normal: { opacity: 1, width: 2, color: '#83c1c5' } },
							z: 4
						}, 
						{
							name: 'MA20',
							type: 'line',
							data: [],
							symbol: 'none',//去除圆点
							smooth: true,
							lineStyle: { normal: { opacity: 1, width: 2, color: '#2DC065' } },
							z: 3
						},
						{
							name: 'MA30',
							type: 'line',
							data: [],
							symbol: 'none',//去除圆点
							smooth: true,
							lineStyle: { normal: { opacity: 1, width: 2, color: '#8601af' } },
							z: 2
						},
						{
								name: 'Volume',
								type: 'bar',
								xAxisIndex: 1,
								yAxisIndex: 1,
								data: []
							},
					]
				};
				myChart.setOption(option);
			}
		}
	}
</script>
<style lang="scss">
	.wrap{
		padding-bottom: 130rpx;
		box-sizing: border-box;
		&__option{
			margin-top: 20rpx;
			padding: 0 24rpx;
			box-sizing: border-box;
			@include flexRowAlign(space-between);
			.option__item{
				color: #999;
				font-size:26rpx;
				// background: #333;
				min-width: 62rpx;
				padding:0 6rpx;
				box-sizing: border-box;
				height: 48rpx;
				border-radius: 6rpx;
				@include flexCenter();
			}
			.option__item--active{
				background: orange;
				color: #000;
			}
		}
		&__ma{
			@include flexRowAlign();
			margin-top: 10rpx;
			padding-left: 20rpx;
			box-sizing: border-box;
			.ma__item{
				color: #ffa500;
				font-size: 24rpx;
				margin-right: 20rpx;
				&:nth-child(2){
					color: #83c1c5;
				}
				&:nth-child(3){
					color: #2DC065;
				}
				&:nth-child(4){
					color: #8601af;
				}
			}
		}
		&__chart{
			margin-top: 10rpx;
			.chart__main{
				height: 700rpx;
				padding-bottom: 16rpx;
			}
			.chart__main--1{
				 // background: #fff;
				
			}
		}
		&__btn{
			@include flexRowAlign(space-between);
			width: 750rpx;
			position: fixed;
			left: 0;
			bottom: 0;
			/* background: #161827; */
			height: 140rpx;
			padding: 0 30rpx;
			box-sizing: border-box;
			.btn__text{
				width: 320rpx;
				height: 98rpx;
				background: #458EF4;
				border-radius: 12rpx;
				@include flexCenter();
				font-size: 36rpx;
				font-weight: 800;
				color: #FFFFFF;
				&:last-child{
					background: #DF4140;
				}
			}
		}
	}
</style>